package com.zzyl.nursing.service.impl;

import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 *
 * @author rouiqasy
 * @date 2025-01-15
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private IAlertDataService alertDataService;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警数据过滤器
     */
    @Override
    public void alertFilter() {
        //查询所有规则
        List<AlertRule> alertRules = alertRuleMapper.selectList(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));

        //判断规则是否生效
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }

        //从redis中查询所有设备上报的数据
        List<Object> deviceDataLists = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_DATA_LATEST);
        //判断数据是否为空
        if (CollUtil.isEmpty(deviceDataLists)) {
            return;
        }
        //遍历数据交给数据报警处理器
        deviceDataLists.forEach(deviceDataList -> {
            List<DeviceData> deviceDatas = (List<DeviceData>) deviceDataList;
            deviceDatas.forEach(deviceData -> {
                alertFilter(deviceData);
            });
        });

    }

    /**
     * 过滤每一条报警数据
     *
     * @param deviceData 设备数据
     */
    private void alertFilter(DeviceData deviceData) {
        //判断当前上报数据是否超过一分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }
        //查询所有的该产品规则和该物模型规则
        List<AlertRule> iotIdRules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, "-1"));

        List<AlertRule> alertRules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getIotId, deviceData.getIotId()));
        //合并
        alertRules.addAll(iotIdRules);
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }

        //根据上述过滤的规则和上报的数据匹配
        alertRules.forEach(alertRule -> {
            deviceDataAlarmHandler(alertRule, deviceData);
        });
    }

    /**
     * 过滤数据是否触发报警规则
     *
     * @param alertRule  报警规则
     * @param deviceData 单个物模型的单个上报数据
     */
    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        // 判断上报时间是否在规则的生效时段内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime start = LocalTime.parse(split[0]);
        LocalTime end = LocalTime.parse(split[1]);
        // 获取上报时间
        LocalTime time = LocalDateTimeUtil.of(deviceData.getAlarmTime()).toLocalTime();
        //判断上报时间是否在规则的生效时段内
        if (time.isBefore(start) || time.isAfter(end)) {
            return;
        }

        //数据比对,上报的数据与规则中的阈值进行比较
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        Double ruleValue = alertRule.getValue();
        int compare = Double.compare(dataValue, ruleValue);

        String durationKey = "iot:duration:" + alertRule.getProductKey() + ":" + alertRule.getIotId() + ":" + alertRule.getFunctionId() + ":" + alertRule.getId();
        String silenceKey = "iot:silence" + alertRule.getProductKey() + ":" + alertRule.getIotId() + ":" + alertRule.getFunctionId() + ":" + alertRule.getId();

        if (("<".equals(alertRule.getOperator()) && compare >= 0) || (">=".equals(alertRule.getOperator()) && compare < 0)) {
            //数据没有达到阈值,删除redis中的报警数
            redisTemplate.delete(durationKey);
            return;
        }

        //判断是否在沉默周期,
        //从redis换从中获取沉默周期如果在沉默周期内,直接return
        Object silencePeriod = redisTemplate.opsForValue().get(silenceKey);
        if (ObjectUtil.isNotEmpty(silencePeriod)) {
            redisTemplate.delete(silenceKey);
            return;
        }
        //判断是否达到了持续周期
        Integer duration = (Integer) redisTemplate.opsForValue().get(durationKey);
        if (ObjectUtil.isEmpty(duration)) {
            duration = 1;
        } else {
            duration += 1;
        }
        //判断如果+1仍未达到持续周期
        if (!duration.equals(alertRule.getDuration())) {
            redisTemplate.opsForValue().set(durationKey, duration);
            return;
        }
        //达到持续周期,报警后,删除redis中的持续周期
        redisTemplate.delete(durationKey);
        //报警过后,进入沉默周期
        redisTemplate.opsForValue().set(silenceKey, 1, alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //数据校验通过,可以保存到alertData表中
        batchSaveAlertData(alertRule, deviceData);
    }

    /**
     * 将报警数据存放到数据库中
     *
     * @param alertRule  报警规则
     * @param deviceData 设备报警数据
     */
    private void batchSaveAlertData(AlertRule alertRule, DeviceData deviceData) {

        List<AlertData> alertDataList = new ArrayList<>();

        List<Long> userIds;
        //查询需要报警的通知人
        if (alertRule.getAlertDataType() == (0)) {
            //老人异常数据
            //判断是固定设备还是随身设备
            if (deviceData.getLocationType() == 0) {
                //随身设备
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            } else {
                //固定设备
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        } else {
            //设备异常数据
            userIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }

        //查询超级管理员
        List<Long> managerUserIds = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");

        //合并用户id
        userIds.addAll(managerUserIds);

        userIds.forEach(userId -> {
            AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
            alertData.setId(null);
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
            alertData.setUserId(userId);
            alertData.setAlertRuleId(alertRule.getId());
            alertData.setType(alertRule.getAlertDataType());
            //状态为未处理0
            alertData.setStatus(0);
            alertData.setAlertReason(alertReason);
            alertDataList.add(alertData);
        });

        //将报警数据批量保存到数据库中
        alertDataService.saveBatch(alertDataList);

        websocketNotity(alertDataList,alertRule,userIds);
    }

    /**
     * websocket推送消息
     * @param alertDataList
     * @param alertRule
     * @param userIds
     */
    private void websocketNotity(List<AlertData> alertDataList, AlertRule alertRule, List<Long> userIds) {
        // 属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertDataList, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        alertNotifyVo.setIsAllConsumer(false);
        // 向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, userIds);
    }

}

